import { ActionTree, GetterTree, Module, MutationTree, Store } from "vuex";
import { RootState } from "../..";
import { API_USER_LOGIN } from "../../../apis/user";
import { USER_LOGIN_REQ_MODEL, USER_LOGIN_RESP_MODEL } from "../../../apis/user_model";
import { setCookie } from "../../../utils/cookie";
import { Actions, AugmentedActionContext, Mutations, UserActionTypes, UserMutationTypes, UserRoleType } from "./types";

const defaultToken: string = '';

/**
 * State
 * 定义state的类型
 */
export type State = {
    token: string,
    UserRoleType: UserRoleType,
}

/**
 * Getters
 * 定义Getters类型
 */
export type Getters = {
    token(state: State): string;
}

const state: State = {
    token: defaultToken,
    UserRoleType: null,
}

const getters: GetterTree<State, RootState> & Getters = {
    token: (state: State) => state.token
}

const mutations: MutationTree<State> & Mutations = {
    [UserMutationTypes.SET_USER_ROLE](state: State, role: UserRoleType) {
        state.UserRoleType = role;
    },
    [UserMutationTypes.SET_USER_TOKEN](state: State, token: string) {
        state.token = token;
    }
}
const actions: ActionTree<State, RootState> & Actions = {
    [UserActionTypes.USER_LOGIN]({ commit }: AugmentedActionContext, params: USER_LOGIN_REQ_MODEL): Promise<void> {
        return new Promise((resolve, reject) => {
            API_USER_LOGIN(params).then((res: USER_LOGIN_RESP_MODEL) => {
                const { data: { token } } = res;
                commit(UserMutationTypes.SET_USER_TOKEN, token)
                setCookie("token", token)
                resolve()
            }).catch((e: any) => {
                reject(e)
            })
        })
    },
}

export const store: Module<State, RootState> = {
    state,
    mutations,
    getters,
    actions,
};